package com.nbjtjc.safe.service.safe;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ImageUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.util.TableTools;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.GreatRiskPointItemBean;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.safe.RiskMarkItemMapper;
import com.nbjtjc.safe.mapper.safe.RiskPointItemMapper;
import com.nbjtjc.safe.mapper.safe.RiskPointMapper;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.model.safe.RiskMarkItem;
import com.nbjtjc.safe.model.safe.RiskPoint;
import com.nbjtjc.safe.model.safe.RiskPointItem;
import com.nbjtjc.safe.model.safe.SafeEnterprise;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import com.nbjtjc.safe.wps.util.upload.oss.OSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import javax.xml.crypto.Data;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class WordgenerateServiceImpl {


    @Value("${word.fxfjPathPrefix}")
    public String fxfjPathPrefix;

    @Value("${word.fxfjWordTemplate}")
    public String fxfjWordTemplate;

    @Value("${word.fjgkPathPrefix}")
    public String fjgkPathPrefix;

    @Value("${word.pcqdPathPrefix}")
    public String pcqdPathPrefix;
    @Value("${word.fjgkWordTemplate}")
    public String fjgkWordTemplate;
    @Value("${word.fxgzkPathPrefix}")
    public String fxgzkPathPrefix;
    @Value("${word.summaryPathPrefix}")
    public String summaryPathPrefix;

    @Value("${word.jdfxqdPathPrefix}")
    public String jdfxqdPathPrefix;

    @Value("${word.riskAreaPicPathPrefix}")
    public String riskAreaPicPathPrefix;
    @Value("${word.fxgzkWordTemplate}")
    public String fxgzWordTemplate;

    @Value("${word.pcqdWordTemplate}")
    public String pcqdWordTemplate;
    @Value("${word.summaryWordTemplate}")
    public String summaryWordTemplate;
    @Value("${word.jdfxqdWordTemplate}")
    public String jdfxqdWordTemplate;

    @Value("${word.riskAreaPicWordTemplate}")
    public String riskAreaPicWordTemplate;

    @Value("${word.reportWordTemplate}")
    public String reportWordTemplate;

    @Value("${word.reportWordOutPath}")
    public String reportOutPath;

    @Value("${word.part4Template}")
    public String part4Template;
    @Autowired
    public RiskPointMapper pointMapper;
    @Autowired
    private RiskPointItemMapper riskPointItemMapper;

    @Autowired
    private OSSUtil ossUtil;
    @Value("${aliyun.oss.domain}")
    private String ossUrlPrefix;

    @Value("${word.riskNoticeCardPicsPath}")
    private String riskNoticeCardPicsPath;
    @Value("${aliyun.oss.domain}")
    private String ossDomain;
    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private RiskMarkItemMapper riskMarkItemMapper;


    private List<Integer> enterpriseIdTypes = new ArrayList<>(Arrays.asList(Constant.SysFileType.ENTERPRISE_FILE.getValue()
            , Constant.SysFileType.FOUR_COLOR_RISK_CHART.getValue()
            , Constant.SysFileType.LOCATION_PIC.getValue(), Constant.SysFileType.SURROUNDING_PIC.getValue()
            , Constant.SysFileType.RISK_AREA_PIC.getValue()));

    private <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> concurrentHashMap = new ConcurrentHashMap<>();
        return t -> concurrentHashMap.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * 生成风险分级清单
     */
    public int generateFxfjWord(int count, int riskType, SafeEnterprise enterprise) throws IOException {
        String dirPath = fxfjPathPrefix + enterprise.getId() + enterprise.getName();
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setEnterpriseId(enterprise.getId());
        params.setRiskType(riskType);
        List<RiskPoint> riskPoints = pointMapper.search(params);
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPoint riskPoint = riskPoints.get(i);
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoint.getId());
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);
            List<RiskPointItem> distinctItems = riskPointItems.stream().filter(distinctByKey(RiskPointItem::getInducedCause)).collect(Collectors.toList());
            InputStream fileInputStream = new FileInputStream(fxfjWordTemplate);
            XWPFDocument doc = new XWPFDocument(fileInputStream);
            List<XWPFTable> tables = doc.getTables();
            XWPFTable table = tables.get(0);
            table.getRow(0).getCell(0).setText("风险点LEC-" + (i + 1));
            distinctItems.forEach(riskPointItem1 -> {
                XWPFTableRow row = table.createRow();
                for (int j = 0; j < 7; j++) {
                    row.createCell();
                }
                List<XWPFTableCell> cellList = row.getTableCells();
                cellList.forEach(cell -> {
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

                    CTTc cttc = cell.getCTTc();
//                cttc.addNewTcPr().addNewShd().setFill("34B6F5");
                    CTP ctp = cttc.getPList().get(0);
                    CTPPr ctppr = ctp.getPPr();
                    if (ctppr == null) {
                        ctppr = ctp.addNewPPr();
                    }
                    CTJc ctjc = ctppr.getJc();
                    if (ctjc == null) {
                        ctjc = ctppr.addNewJc();
                    }
                    ctjc.setVal(STJc.CENTER); //水平居中
                });
                System.out.println(row.getTableCells().size());
            });
            List<XWPFTableRow> tableRows = table.getRows();
            String step = distinctItems.get(0).getStepOrUnit();
            List<Integer> indexList = new ArrayList<>();
            for (int j = 0; j < distinctItems.size(); j++) {
                String stepName = distinctItems.get(j).getStepOrUnit();
                if (!stepName.equals(step)) {
                    step = stepName;
                    indexList.add(j - 1);
                }
                if (j == distinctItems.size() - 1) {
                    indexList.add(distinctItems.size() - 1);
                }
                XWPFTableRow row = tableRows.get(j + 2);
                RiskPointItem item = distinctItems.get(j);
                row.getCell(0).setText(1 + "");
                row.getCell(1).setText(riskPoint.getRiskTypeName());
                row.getCell(2).setText(riskPoint.getPointName());
                row.getCell(3).setText((j + 1) + "");
                row.getCell(4).setText(item.getStepOrUnit());
                row.getCell(5).setText(item.getInducedCause());
                row.getCell(6).setText(item.getAccidentName());
                String lecValue = item.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    row.getCell(7).setText(lecJson.getString("L"));
                    row.getCell(8).setText(lecJson.getString("E"));
                    row.getCell(9).setText(lecJson.getString("C"));
//                    row.getCell(10).setText(lecJson.getString("D"));
                    row.getCell(11).setText(item.getEvaluationResultValue());
//                    row.getCell(12).setText(item.getEvaluationResultName());
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        String dVal = NumberUtil.roundStr(lecJson.getString("D"), 2);
                        row.getCell(10).setText(dVal);
                        if (result < 70) {
                            row.getCell(11).setColor("34B6F5");
                        }
                        if (result >= 70 & result < 160) {
                            row.getCell(11).setColor("FBFF00");
                        }
                        if (result >= 160 & result < 320) {
                            row.getCell(11).setColor("FBCA00");
                        }
                        if (result > 320) {
                            row.getCell(11).setColor("FA0000");
                        }
                    } else {
                        row.getCell(10).setText(lecJson.getString("D"));
                    }
                } else {
                    System.out.println("非法json" + riskPoint.toString());
                }
            }
            System.out.println(table.getRows().size());
            TableTools.mergeCellsVertically(table, 0, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 1, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 2, 2, 1 + distinctItems.size());
            for (int j = 0; j < indexList.size(); j++) {
                if (j == 0) {
                    TableTools.mergeCellsVertically(table, 4, 2, 2 + indexList.get(j));
                } else {
                    TableTools.mergeCellsVertically(table, 4, 2 + indexList.get(j - 1) + 1, 2 + indexList.get(j));
                }
            }
            try {

                File f = new File(dirPath + File.separator + "LEC-" + (i + 1 + count) + ".docx");
                if (f.exists() == false) {
                    f.createNewFile();
                } else {
                    f.delete();
                    f.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(f);
                doc.write(out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return riskPoints.size() + count;
    }

    public int generateFjgkWord(int count, SafeEnterprise enterprise) throws IOException {
        String dirPath = fjgkPathPrefix + enterprise.getId() + enterprise.getName() + File.separator;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setEnterpriseId(enterprise.getId());
        List<RiskPoint> riskPoints = pointMapper.search(params);
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoints.get(i).getId());
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);
            List<RiskPointItem> distinctItems = riskPointItems.stream().filter(distinctByKey(RiskPointItem::getInducedCause)).collect(Collectors.toList());
            InputStream fileInputStream = new FileInputStream(fjgkWordTemplate);
            XWPFDocument doc = new XWPFDocument(fileInputStream);
            List<XWPFTable> tables = doc.getTables();
            XWPFTable table = tables.get(0);
            table.getRow(0).getCell(0).setText("管控措施HC-" + (i + 1));
            distinctItems.forEach(riskPointItem1 -> {
                XWPFTableRow row = table.createRow();
                for (int j = 0; j < 10; j++) {
                    row.createCell();

                }
                List<XWPFTableCell> cellList = row.getTableCells();
                cellList.forEach(cell -> {
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

                    CTTc cttc = cell.getCTTc();
                    CTP ctp = cttc.getPList().get(0);
                    CTPPr ctppr = ctp.getPPr();
                    if (ctppr == null) {
                        ctppr = ctp.addNewPPr();
                    }
                    CTJc ctjc = ctppr.getJc();
                    if (ctjc == null) {
                        ctjc = ctppr.addNewJc();
                    }
                    ctjc.setVal(STJc.CENTER); //水平居中
                });
                System.out.println(row.getTableCells().size());
            });
            List<XWPFTableRow> tableRows = table.getRows();
            String step = distinctItems.get(0).getStepOrUnit();
            List<Integer> indexList = new ArrayList<>();
            for (int j = 0; j < distinctItems.size(); j++) {
                String stepName = distinctItems.get(j).getStepOrUnit();
                if (!stepName.equals(step)) {
                    step = stepName;
                    indexList.add(j - 1);
                }
                if (j == distinctItems.size() - 1) {
                    indexList.add(distinctItems.size() - 1);
                }
                XWPFTableRow row = tableRows.get(j + 2);
                RiskPointItem item = distinctItems.get(j);
                row.getCell(0).setText(1 + "");
                row.getCell(1).setText(riskPoints.get(i).getRiskTypeName());
                row.getCell(2).setText(riskPoints.get(i).getPointName());
                row.getCell(3).setText((j + 1) + "");
                row.getCell(4).setText(item.getStepOrUnit());
                row.getCell(5).setText(item.getInducedCause());
                row.getCell(6).setText(item.getAccidentName());

                row.getCell(7).setText(item.getEvaluationResultValue());
                row.getCell(8).setText(item.getEngineeringTechnology());
                String measures = "";
                if (StringUtils.isNotEmpty(item.getManageMeasures())) {
                    measures = measures + item.getManageMeasures();
                }
                if (StringUtils.isNotEmpty(item.getControlMeasures())) {
                    measures = measures + item.getControlMeasures();
                }
                row.getCell(9).setText(measures);
                row.getCell(10).setText(item.getTrainMeasures());
                row.getCell(11).setText(item.getPersonalProtection());
                row.getCell(12).setText(item.getEmergencyMeasures());
                String lecValue = item.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        if (result < 70) {
                            row.getCell(7).setColor("34B6F5");
                            row.getCell(16).setText("√");
                        }
                        if (result >= 70 & result < 160) {
                            row.getCell(7).setColor("FBFF00");
                            row.getCell(16).setText("√");
                            row.getCell(15).setText("√");
                        }
                        if (result >= 160 & result < 320) {
                            row.getCell(7).setColor("FBCA00");
                            row.getCell(16).setText("√");
                            row.getCell(15).setText("√");
                            row.getCell(14).setText("√");
                        }
                        if (result > 320) {
                            row.getCell(7).setColor("FA0000");
                            row.getCell(16).setText("√");
                            row.getCell(15).setText("√");
                            row.getCell(14).setText("√");
                            row.getCell(13).setText("√");
                        }
                    }
                } else {
                    System.out.println("非法json" + item.toString());
                }


            }
            System.out.println(table.getRows().size());
            TableTools.mergeCellsVertically(table, 0, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 1, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 2, 2, 1 + distinctItems.size());
            for (int j = 0; j < indexList.size(); j++) {
                if (j == 0) {
                    TableTools.mergeCellsVertically(table, 4, 2, 2 + indexList.get(j));
                } else {
                    TableTools.mergeCellsVertically(table, 4, 2 + indexList.get(j - 1) + 1, 2 + indexList.get(j));
                }
            }
            try {

                File f = new File(dirPath + "LEC-" + (count + i + 1) + ".docx");
                if (f.exists() == false) {
                    f.createNewFile();
                } else {
                    f.delete();
                    f.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(f);
                doc.write(out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return count;
    }

    /**
     * 排查清单
     *
     * @return
     */
    public int generatePcqdWord(int riskPointType, SafeEnterprise safeEnterprise) throws IOException {
        String dirPath = pcqdPathPrefix + safeEnterprise.getId() + safeEnterprise.getName() + File.separator;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setRiskType(riskPointType);
        params.setEnterpriseId(safeEnterprise.getId());
        List<RiskPoint> riskPoints = pointMapper.search(params);
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoints.get(i).getId());
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);
            List<RiskPointItem> distinctItems = riskPointItems.stream().filter(distinctByKey(RiskPointItem::getInducedCause)).collect(Collectors.toList());
            InputStream fileInputStream = new FileInputStream(pcqdWordTemplate);
            XWPFDocument doc = new XWPFDocument(fileInputStream);
            List<XWPFTable> tables = doc.getTables();
            XWPFTable table = tables.get(0);
            table.getRow(0).getCell(0).setText("管控点HC-" + (i + 1) + riskPoints.get(i).getPointName());
            distinctItems.forEach(riskPointItem1 -> {
                XWPFTableRow row = table.createRow();
                for (int j = 0; j < 9; j++) {
                    row.createCell();

                }
                List<XWPFTableCell> cellList = row.getTableCells();
                cellList.forEach(cell -> {
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                    CTTc cttc = cell.getCTTc();
                    CTP ctp = cttc.getPList().get(0);
                    CTPPr ctppr = ctp.getPPr();
                    if (ctppr == null) {
                        ctppr = ctp.addNewPPr();
                    }
                    CTJc ctjc = ctppr.getJc();
                    if (ctjc == null) {
                        ctjc = ctppr.addNewJc();
                    }
                    ctjc.setVal(STJc.CENTER); //水平居中
                });
                System.out.println(row.getTableCells().size());
            });
            List<XWPFTableRow> tableRows = table.getRows();
            String step = distinctItems.get(0).getStepOrUnit();
            List<Integer> indexList = new ArrayList<>();
            for (int j = 0; j < distinctItems.size(); j++) {
                String stepName = distinctItems.get(j).getStepOrUnit();
                if (!stepName.equals(step)) {
                    step = stepName;
                    indexList.add(j - 1);
                }
                if (j == distinctItems.size() - 1) {
                    indexList.add(distinctItems.size() - 1);
                }
                XWPFTableRow row = tableRows.get(j + 2);
                RiskPointItem item = distinctItems.get(j);
                row.getCell(0).setText(1 + "");
                row.getCell(1).setText(riskPoints.get(i).getRiskTypeName());
                row.getCell(2).setText(riskPoints.get(i).getPointName());
                row.getCell(3).setText((j + 1) + "");
                row.getCell(4).setText(item.getStepOrUnit());
                row.getCell(5).setText(item.getInducedCause());
                row.getCell(6).setText(item.getAccidentName());

                row.getCell(7).setText(item.getEvaluationResultValue());
                row.getCell(8).setText(item.getEngineeringTechnology());
                String measures = "";
                if (StringUtils.isNotEmpty(item.getManageMeasures())) {
                    measures = measures + item.getManageMeasures();
                }
                if (StringUtils.isNotEmpty(item.getControlMeasures())) {
                    measures = measures + item.getControlMeasures();
                }
                row.getCell(9).setText(measures);
                row.getCell(10).setText(item.getTrainMeasures());
                row.getCell(11).setText(item.getPersonalProtection());
                row.getCell(12).setText(item.getEmergencyMeasures());
                String lecValue = item.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        if (result < 70) {
                            row.getCell(7).setColor("34B6F5");
                            row.getCell(13).setText("√");
                        }
                        if (result >= 70 & result < 160) {
                            row.getCell(7).setColor("FBFF00");
                            row.getCell(13).setText("√");
                            row.getCell(14).setText("√");
                        }
                        if (result >= 160 & result < 320) {
                            row.getCell(7).setColor("FBCA00");
                            row.getCell(13).setText("√");
                            row.getCell(14).setText("√");
                            row.getCell(15).setText("√");
                        }
                        if (result > 320) {
                            row.getCell(7).setColor("FA0000");
                            row.getCell(16).setText("√");
                            row.getCell(15).setText("√");
                            row.getCell(14).setText("√");
                            row.getCell(13).setText("√");
                        }
                    }
                } else {
                    System.out.println("非法json" + item.toString());
                }
            }
            System.out.println(table.getRows().size());
            TableTools.mergeCellsVertically(table, 0, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 1, 2, 1 + distinctItems.size());
            TableTools.mergeCellsVertically(table, 2, 2, 1 + distinctItems.size());
            for (int j = 0; j < indexList.size(); j++) {
                if (j == 0) {
                    TableTools.mergeCellsVertically(table, 4, 2, 2 + indexList.get(j));
                } else {
                    TableTools.mergeCellsVertically(table, 4, 2 + indexList.get(j - 1) + 1, 2 + indexList.get(j));
                }
            }
            try {

                File f = new File(dirPath + "LEC-" + (i + 1) + ".docx");
                if (f.exists() == false) {
                    f.createNewFile();
                } else {
                    f.delete();
                    f.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(f);
                doc.write(out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public String generateSummary(SafeEnterprise enterprise) throws IOException {
        String dirPath = summaryPathPrefix + enterprise.getId() + enterprise.getName() + File.separator;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setEnterpriseId(enterprise.getId());
        List<RiskPoint> riskPoints = pointMapper.search(params);
        Map<String, Object> renderMap = new HashMap<>();
        renderMap.put("enterpriseName", enterprise.getName());
        Set<String> mainDangerSet = new HashSet<>();
        Set<String> secondaryDangerSet = new HashSet<>();
        Set<String> secondLevelDepartmentsSet = new HashSet<>();
        Set<String> thirdLevelDepartmentsSet = new HashSet<>();
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPoint riskPoint = riskPoints.get(i);
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoint.getId());
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);
            riskPointItems.forEach(pointItem -> {
                String lecValue = pointItem.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        if (result >= 160) {
                            mainDangerSet.add(pointItem.getAccidentName());
                        } else {
                            secondaryDangerSet.add(pointItem.getAccidentName());
                        }
                        if (result >= 70 & result < 160) {
                            secondLevelDepartmentsSet.remove(riskPoint.getDepartment());
                            thirdLevelDepartmentsSet.add(riskPoint.getDepartment());
                        }
                        if (result >= 160 & result < 320) {
                            secondLevelDepartmentsSet.add(riskPoint.getDepartment());
                            thirdLevelDepartmentsSet.remove(riskPoint.getDepartment());
                        }
                    }
                }
            });
        }
        String mainDanger = "";
        String secondaryDanger = "";
        String secondLevelDepartments = "";
        String thirdLevelDepartments = "";
        for (String str : mainDangerSet) {
            mainDanger = mainDanger + "、" + str;
        }
        for (String str : secondaryDangerSet) {
            secondaryDanger = secondaryDanger + "、" + str;
        }
        for (String str : secondLevelDepartmentsSet) {
            secondLevelDepartments = secondLevelDepartments + "、" + str;
        }
        for (String str : thirdLevelDepartmentsSet) {
            thirdLevelDepartments = thirdLevelDepartments + "、" + str;
        }
        if (StringUtils.isEmpty(mainDanger)) {
            mainDanger = "无";
        }
        if (StringUtils.isEmpty(secondaryDanger)) {
            secondaryDanger = "无";
        }
        if (StringUtils.isEmpty(secondLevelDepartments)) {
            secondLevelDepartments = "无";
        }
        if (StringUtils.isEmpty(thirdLevelDepartments)) {
            thirdLevelDepartments = "无";
        }
        renderMap.put("mainDanger", mainDanger);
        renderMap.put("secondaryDanger", secondaryDanger);
        renderMap.put("secondLevelDepartments", secondLevelDepartments);
        renderMap.put("thirdLevelDepartments", thirdLevelDepartments);
        String summaryFileName = enterprise.getName() + "-" + enterprise.getId() + "总结部分.docx";

        File templateFile = new File(summaryWordTemplate);
        XWPFTemplate template = XWPFTemplate.compile(templateFile).render(renderMap);
        FileOutputStream outputStream = new FileOutputStream(new File(dirPath + summaryFileName));
        template.write(outputStream);
        outputStream.flush();
        outputStream.close();
        template.close();
        return dirPath + summaryFileName;
    }

    public void generateFxgzkWord(int count, SafeEnterprise enterprise, int level) {
        String dirPath = fxgzkPathPrefix + enterprise.getId() + enterprise.getName() + File.separator;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setEnterpriseId(enterprise.getId());
        List<RiskPoint> riskPoints = pointMapper.search(params);
        int lecCount=1;
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoints.get(i).getId());
            riskPointItem.setEvaluationResultName("一般风险");
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);
            riskPointItem.setEvaluationResultName("较大风险");
            riskPointItems.addAll(riskPointItemMapper.search(riskPointItem));
            riskPointItem.setEvaluationResultName("重大风险");
            riskPointItems.addAll(riskPointItemMapper.search(riskPointItem));
            compareRiskPointItemPic(riskPointItems);
            Map<String, List<RiskPointItem>> pointMap = new HashMap<>();
            riskPointItems.forEach(item -> {
                String key=item.getRiskPointId()+item.getDangerousSource()+item.getAccidentName()+item.getInducedCause();
                if (pointMap.containsKey(key)) {
                    pointMap.get(key).add(item);
                } else {
                    List<RiskPointItem> itemList = new ArrayList<>();
                    itemList.add(item);
                    pointMap.put(key, itemList);
                }
            });
            List<String> keys = new ArrayList<>(pointMap.keySet());
            for (int j = 0; j < keys.size(); j++) {
                String dangerousSource = keys.get(j);
                List<RiskPointItem> riskPointItemList = pointMap.get(dangerousSource);
                String manageMeasures = "";
                List<RiskMarkItem> riskMarkItemList = new ArrayList<>();
                for (int n = 0; n < riskPointItemList.size(); n++) {
                    manageMeasures += (n + 1) + "." + riskPointItemList.get(n).getControlMeasures() + "\n\r";
                    riskMarkItemList.addAll(riskPointItemList.get(n).getRiskMarkItemList());
                }
                InputStream fileInputStream = null;
                try {
                    fileInputStream = new FileInputStream(fxgzWordTemplate);
                    XWPFDocument doc = null;
                    doc = new XWPFDocument(fileInputStream);
                    RiskPointItem pointItem = riskPointItemList.get(0);
                    List<XWPFTableRow> rows = doc.getTables().get(0).getRows();
                    rows.get(0).getCell(1).setText(riskPoints.get(i).getPointName());
                    String lecValue = pointItem.getEvaluationResultBase();
                    if (JSON.isValid(lecValue)) {
                        JSONObject lecJson = null;
                        if (JSONUtil.isJsonArray(lecValue)) {
                            lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                        } else {
                            lecJson = JSON.parseObject(lecValue);
                        }
                        if (NumberUtil.isNumber(lecJson.getString("D"))) {
                            int result = NumberUtil.parseInt(lecJson.getString("D"));
                            if (result < 70) {
                                rows.get(2).getCell(1).setColor("34B6F5");
                                rows.get(2).getCell(1).setText("低风险/蓝色");
                                rows.get(4).getCell(1).setText("班组/岗位");
                                rows.get(5).getCell(1).setText("员工");
                            }
                            if (result >= 70 & result < 160) {
                                rows.get(2).getCell(1).setColor("FBFF00");
                                rows.get(2).getCell(1).setText("一般风险/黄色");
                                rows.get(4).getCell(1).setText("车间");
                                rows.get(5).getCell(1).setText("车间主任");
                            }
                            if (result >= 160 & result < 320) {
                                rows.get(2).getCell(1).setColor("FBCA00");
                                rows.get(1).getCell(3).setText("较大风险/橙色");
                                rows.get(4).getCell(1).setText("工厂");
                                rows.get(5).getCell(1).setText("厂长");
                            }
                            if (result > 320) {
                                rows.get(2).getCell(1).setColor("FA0000");
                                rows.get(2).getCell(1).setText("重大风险");
                                rows.get(4).getCell(1).setText("公司");
                                rows.get(5).getCell(1).setText("经理");
                            }
                        }
                    } else {
                        System.out.println("非法json" + pointItem.toString());
                    }

                    rows.get(1).getCell(1).setText(riskPoints.get(i).getId()+"FXGZ-" + (lecCount));
                    rows.get(2).getCell(3).setText(riskPoints.get(i).getDepartment());
                    rows.get(0).getCell(3).setText(pointItem.getInducedCause());
//                    rows.get(3).getCell(1).setText(pointItem.getEvaluationValue());
                    rows.get(3).getCell(1).setText(pointItem.getAccidentName());
                    rows.get(6).getCell(2).setText(pointItem.getEmergencyMeasures());
                    rows.get(4).getCell(3).setText(manageMeasures);
                    List<String> files = new ArrayList<>();
//                    files.add("D:\\safe\\63B21488-35D6-414A-A0CE-45A4A05FAA77.png");
//                    files.add("/Users/guqianbin/Downloads/119D9CD7-540B-4E0A-B4F1-12F95D89A6E1.png");
                    //todo 根据配置设置要添加的图片
//                    setCellImage(rows.get(7).getCell(0), files);
                    insertCellImage(riskMarkItemList, rows.get(7).getCell(0));

                    File f = new File(dirPath + "LEC-" + (lecCount) + ".docx");
                    if (f.exists() == false) {
                        f.createNewFile();
                    } else {
                        f.delete();
                        f.createNewFile();
                    }
                    FileOutputStream out = new FileOutputStream(f);
                    doc.write(out);
                    out.close();
                    lecCount++;

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void insertCellImage(List<RiskMarkItem> riskMarkItemList, XWPFTableCell cell) {
        if (CollectionUtil.isNotEmpty(riskMarkItemList)) {
            List<String> insertFiles = new ArrayList<>();
            Set<String> imageSet=new HashSet<>();
            riskMarkItemList.forEach(riskMarkItem -> {
                String iconUrl = riskMarkItem.getIconUrl();
                String fileName = iconUrl.substring(iconUrl.lastIndexOf("/") + 1, iconUrl.indexOf("png")) + ".png";
                insertFiles.add(riskNoticeCardPicsPath + fileName);
                imageSet.add(riskNoticeCardPicsPath + fileName);
            });
            setCellImage(cell, new ArrayList<>(imageSet));
        }
    }

    /**
     * part7第七部分，二级及以上风险清单
     */
    public String generateGreateRiskPoint(SafeEnterprise safeEnterprise) throws IOException {
        String dirPath = jdfxqdPathPrefix + safeEnterprise.getId() + safeEnterprise.getName() + File.separator;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        RiskPoint params = new RiskPoint();
        params.setGenerateWord(1);
        params.setEnterpriseId(safeEnterprise.getId());
        List<RiskPoint> riskPoints = pointMapper.search(params);
        InputStream fileInputStream = new FileInputStream(jdfxqdWordTemplate);
        XWPFDocument doc = new XWPFDocument(fileInputStream);
        int count = 2;
        int index = 1;
        for (int i = 0; i < riskPoints.size(); i++) {
            RiskPointItem riskPointItem = new RiskPointItem();
            riskPointItem.setRiskPointId(riskPoints.get(i).getId());
            List<RiskPointItem> riskPointItems = riskPointItemMapper.search(riskPointItem);

            List<XWPFTable> tables = doc.getTables();
            XWPFTable table = tables.get(0);
            riskPointItems.forEach(riskPointItem1 -> {
                String lecValue = riskPointItem1.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        if (result >= 160 & result < 320) {
                            XWPFTableRow row = table.createRow();
                            for (int j = 0; j < 7; j++) {
                                row.createCell();

                            }
                            List<XWPFTableCell> cellList = row.getTableCells();
                            cellList.forEach(cell -> {
                                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

                                CTTc cttc = cell.getCTTc();
                                CTP ctp = cttc.getPList().get(0);
                                CTPPr ctppr = ctp.getPPr();
                                if (ctppr == null) {
                                    ctppr = ctp.addNewPPr();
                                }
                                CTJc ctjc = ctppr.getJc();
                                if (ctjc == null) {
                                    ctjc = ctppr.addNewJc();
                                }
                                ctjc.setVal(STJc.CENTER); //水平居中
                            });
                            System.out.println(row.getTableCells().size());
                        }
                    }
                } else {
                    System.out.println("非法json" + riskPointItem1.toString());
                }

            });
            List<XWPFTableRow> tableRows = table.getRows();

            for (int j = 0; j < riskPointItems.size(); j++) {
                RiskPointItem item = riskPointItems.get(j);

                String lecValue = item.getEvaluationResultBase();
                if (JSON.isValid(lecValue)) {
                    JSONObject lecJson = null;
                    if (JSONUtil.isJsonArray(lecValue)) {
                        lecJson = JSON.parseArray(lecValue).getJSONObject(0);
                    } else {
                        lecJson = JSON.parseObject(lecValue);
                    }
                    if (NumberUtil.isNumber(lecJson.getString("D"))) {
                        int result = NumberUtil.parseInt(lecJson.getString("D"));
                        if (result >= 160 & result < 320) {
                            XWPFTableRow row = tableRows.get(count);
                            row.getCell(0).setText(index + "");
                            row.getCell(1).setText(riskPoints.get(i).getRiskTypeName());
                            row.getCell(2).setText(riskPoints.get(i).getPointName());
                            row.getCell(3).setText(item.getInducedCause());
                            row.getCell(4).setText(item.getAccidentName());
                            row.getCell(5).setText(item.getEvaluationResultValue());
                            row.getCell(6).setText(item.getControlMeasures());
                            String measures = "";
                            if (StringUtils.isNotEmpty(item.getManageMeasures())) {
                                measures = measures + item.getManageMeasures();
                            }
                            if (StringUtils.isNotEmpty(item.getControlMeasures())) {
//                                measures = measures + item.getControlMeasures();
                            }
                            row.getCell(7).setText(measures);
                            row.getCell(8).setText(item.getTrainMeasures());

                            row.getCell(9).setText(item.getPersonalProtection());
                            row.getCell(10).setText(item.getEmergencyMeasures());
                            row.getCell(5).setColor("FBCA00");

                            row.getCell(14).setText("√");
                            row.getCell(13).setText("√");
                            row.getCell(12).setText("√");
                            if (result > 320) {
                                row.getCell(5).setColor("FA0000");
                                row.getCell(11).setText("√");
                            }
                            count++;
                            index++;
                        }

                    }
                } else {
                    System.out.println("非法json" + item.toString());
                }


            }

        }
        String fileName = safeEnterprise.getName() + "较大风险清单.docx";

        try {

            File f = new File(dirPath + fileName);
            if (f.exists() == false) {
                f.createNewFile();
            } else {
                f.delete();
                f.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(f);
            doc.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dirPath + fileName;

    }

    public String generateRiskAreaPic(SafeEnterprise safeEnterprise) throws IOException {
        List<Integer> enterpriseIds = new ArrayList<>();
        enterpriseIds.add(safeEnterprise.getId());
        List<SysFile> sysFiles = sysFileMapper.findByContentIdsAndContentTypes(enterpriseIds, enterpriseIdTypes);
        Map<String, Object> renderMap = new HashMap<>();
        sysFiles.forEach(sysFile -> {
            if (sysFile.getContentType().equals(Constant.SysFileType.RISK_AREA_PIC.getValue())) {
                HttpUtil.downloadFile(ossDomain + "/" + sysFile.getPath(), new File(riskAreaPicPathPrefix + sysFile.getFileName()));
                File image = new File(riskAreaPicPathPrefix + sysFile.getFileName());
                if (image.exists()) {
                    BufferedImage bufferedImage = ImageUtil.read(image);
                    double percent = NumberUtil.div(bufferedImage.getHeight(), bufferedImage.getWidth());
                    renderMap.put("riskAreaPic", new PictureRenderData(600, new Double(600 * percent).intValue(), image));
                }
            }
        });
        String destReportPath = riskAreaPicPathPrefix + safeEnterprise.getName() + "-风险区域四色图.docx";
        File templateFile = new File(riskAreaPicWordTemplate);
        XWPFTemplate template = XWPFTemplate.compile(templateFile).render(renderMap);
        FileOutputStream outputStream = new FileOutputStream(new File(destReportPath));
        template.write(outputStream);
        outputStream.flush();
        outputStream.close();
        template.close();

        return destReportPath;
    }

    /**
     * 查询辨识记录的风险标识
     *
     * @param riskPointItems
     */
    public void compareRiskPointItemPic(List<RiskPointItem> riskPointItems) {
        if (CollectionUtil.isEmpty(riskPointItems)) {
            return;
        }
        List<Integer> riskPointItemIds = riskPointItems.stream().map(RiskPointItem::getId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(riskPointItemIds)) {
            return;
        }
        List<RiskMarkItem> riskMarkItems = riskMarkItemMapper.findByRiskPointIds(riskPointItemIds);
        if (CollectionUtil.isEmpty(riskMarkItems)) {
            return;
        }
        Map<Integer, List<RiskMarkItem>> markMap = new HashMap<>();
        riskMarkItems.forEach(mark -> {
            if (markMap.containsKey(mark.getItemId())) {
                markMap.get(mark.getItemId()).add(mark);
            } else {
                List<RiskMarkItem> riskMarkItemList = new ArrayList<>();
                riskMarkItemList.add(mark);
                markMap.put(mark.getItemId(), riskMarkItemList);
            }
        });
        riskPointItems.forEach(pointItem -> {
            if (markMap.containsKey(pointItem.getId())) {
                pointItem.setRiskMarkItemList(markMap.get(pointItem.getId()));
            }
        });


    }

    public List<File> mergeWord(String dirPath) throws Exception {
        File fxfjDir = new File(dirPath);
        File[] fxfjFile = fxfjDir.listFiles();
        List<File> files = new ArrayList<>();
        if (fxfjFile.length > 0) {
            files.addAll(sortFileByName(fxfjFile));
            return files;
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 正则提取文件名编号数字，排序
     *
     * @param files
     * @return
     */
    private static List<File> sortFileByName(File[] files) {
        List<File> fileList = new ArrayList<>();
        fileList.addAll(Arrays.asList(files));
        fileList.sort(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(o1.getName());
                int num1 = NumberUtil.parseInt(m.replaceAll("").trim());
                Matcher m2 = p.matcher(o2.getName());
                int num2 = NumberUtil.parseInt(m2.replaceAll("").trim());
                if (num1 > num2) {
                    return 1;
                }
                if (num1 < num2) {
                    return -1;
                }
                return 0;
            }
        });
        return fileList;
    }

    /**
     * 输出生成的 报告路径
     *
     * @param safeEnterprise
     * @return
     */
    public String fillMainWord(SafeEnterprise safeEnterprise) throws IOException {
        List<Integer> enterpriseIds = new ArrayList<>();
        enterpriseIds.add(safeEnterprise.getId());
        List<SysFile> sysFiles = sysFileMapper.findByContentIdsAndContentTypes(enterpriseIds, enterpriseIdTypes);
        Map<String, Object> renderMap = new HashMap<>();
        sysFiles.forEach(sysFile -> {
            if (sysFile.getContentType().equals(Constant.SysFileType.LOCATION_PIC.getValue())) {
                HttpUtil.downloadFile(ossDomain + "/" + sysFile.getPath(), new File(reportOutPath + sysFile.getFileName()));
                File image = new File(reportOutPath + sysFile.getFileName());
                if (image.exists()) {
                    BufferedImage bufferedImage = ImageUtil.read(image);
                    double percent = NumberUtil.div(bufferedImage.getHeight(), bufferedImage.getWidth());
                    renderMap.put("locationPic", new PictureRenderData(600, new Double(600 * percent).intValue(), image));
                }
            }
            if (sysFile.getContentType().equals(Constant.SysFileType.SURROUNDING_PIC.getValue())) {
                HttpUtil.downloadFile(ossDomain + "/" + sysFile.getPath(), new File(reportOutPath + sysFile.getFileName()));
                File image = new File(reportOutPath + sysFile.getFileName());
                if (image.exists()) {
                    BufferedImage bufferedImage = ImageUtil.read(image);
                    double percent = NumberUtil.div(bufferedImage.getHeight(), bufferedImage.getWidth());

                    renderMap.put("surroundPic", new PictureRenderData(600, new Double(600 * percent).intValue(), image));
                }
            }
            if (sysFile.getContentType().equals(Constant.SysFileType.RISK_AREA_PIC.getValue())) {
                HttpUtil.downloadFile(ossDomain + "/" + sysFile.getPath(), new File(reportOutPath + sysFile.getFileName()));
                File image = new File(reportOutPath + sysFile.getFileName());
                if (image.exists()) {
                    BufferedImage bufferedImage = ImageUtil.read(image);
                    double percent = NumberUtil.div(bufferedImage.getHeight(), bufferedImage.getWidth());
                    renderMap.put("riskAreaPic", new PictureRenderData(600, new Double(600 * percent).intValue(), image));
                }
            }
        });
        renderMap.put("enterpriseNameFirst", safeEnterprise.getName());
        renderMap.put("enterpriseNameSecond", safeEnterprise.getName());
        renderMap.put("enterpriseName", safeEnterprise.getName());
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        renderMap.put("year", year);
        renderMap.put("month", month);
        String destReportPath = reportOutPath + safeEnterprise.getName() + "-" + safeEnterprise.getId() + year + "-" + month + "-" + day + ".docx";

        File templateFile = new File(reportWordTemplate);
        XWPFTemplate template = XWPFTemplate.compile(templateFile).render(renderMap);
        FileOutputStream outputStream = new FileOutputStream(new File(destReportPath));
        template.write(outputStream);
        outputStream.flush();
        outputStream.close();
        template.close();
        return destReportPath;
    }

    public Result generateMainWord(SafeEnterprise enterprise) throws Exception {

        Result result = new Result();
        File reportDir = new File(reportOutPath);
        if (!reportDir.exists()) {
            reportDir.mkdirs();
        }

        int count = 0;
        //part1
        String destReportPath = fillMainWord(enterprise);
        //part2  风险分级清单
        count = generateFxfjWord(count, 3, enterprise);//作业活动
        count = generateFxfjWord(count, 1, enterprise);//设施设备
        count = generateFxfjWord(count, 2, enterprise);//部位场所
        //part3  分级管控措施
        count = generateFjgkWord(0, enterprise);//分级管控清单
        //part4暂时不用生成
        //part5 排查清单
        generatePcqdWord(1, enterprise);
        //part6 总结
        String summaryPath = generateSummary(enterprise);
        //part7 较大风险清单
        String greateRiskPointPath = generateGreateRiskPoint(enterprise);
        //part8 四色图

        String riskAreaPicPath = generateRiskAreaPic(enterprise);
        //part9 风险告知卡
        generateFxgzkWord(0, enterprise, 1);
        File mainReportTempalte = new File(reportWordTemplate);

        List<File> mergeFiles = new ArrayList<>();
        if (new File(destReportPath).exists()) {
            //part1
//            mergeFiles.add(new File(destReportPath));
        }
        //part2 风险清单
        mergeFiles.addAll(mergeWord(fxfjPathPrefix + enterprise.getId() + enterprise.getName() + File.separator));
        //part3 分级管控措施
        mergeFiles.addAll(mergeWord(fjgkPathPrefix + enterprise.getId() + enterprise.getName() + File.separator));
        //part4
        if(new File(part4Template).exists()){
            mergeFiles.add(new File(part4Template));
        }
        //part5 排查清单
        mergeFiles.addAll(mergeWord(pcqdPathPrefix + enterprise.getId() + enterprise.getName() + File.separator));
        //part6 总结
        if(new File(summaryPath).exists()){
            mergeFiles.add(new File(summaryPath));
        }
        //part7
        if(new File(greateRiskPointPath).exists()){
            mergeFiles.add(new File(greateRiskPointPath));
        }
        //part8 四色风险图
        mergeFiles.add(new File(riskAreaPicPath));
        //part9
        mergeFiles.addAll(mergeWord(fxgzkPathPrefix + enterprise.getId() + enterprise.getName() + File.separator));

        if (CollectionUtil.isNotEmpty(mergeFiles)) {
            int size = mergeFiles.size();
            int mergeCount = 0;
            while (mergeCount < size) {
                NiceXWPFDocument mainWord = null;

                if (mergeCount > 0) {
                    mainWord = new NiceXWPFDocument(new FileInputStream(new File(destReportPath)));
                } else {
                    mainWord = new NiceXWPFDocument(new FileInputStream(destReportPath));
                }
                for (int i = 0; i < 3; i++) {
                    if (mergeCount >= size) {
                        break;
                    }
                    NiceXWPFDocument reportFile = new NiceXWPFDocument(new FileInputStream(mergeFiles.get(mergeCount)));
                    mergeCount++;
                    mainWord = mainWord.merge(reportFile);
                }
                File dest = new File(destReportPath);
                FileOutputStream out = new FileOutputStream(dest);
                mainWord.write(out);
                mainWord.close();
                out.close();
            }
        }
        File report = new File(destReportPath);
        String ossPath = ossUtil.simpleUploadFile(report);
        SysFile sysFile = new SysFile();
        sysFile.setPath(ossPath);
        sysFile.setFileName(report.getName());
        sysFile.setContentType(Constant.SysFileType.ENTERPRISE_REPORT_FILE.getValue());
        sysFile.setContentId(enterprise.getId());
        sysFile.setCreateTime(new Date());
//        sysFile.setUserId(MyShiroUtils.getSessionUserId());
        sysFile.setUserId(1);
        sysFile.setSize(NumberUtil.parseInt(report.length() + ""));
        sysFile.setHistory(0);
        sysFileMapper.insert(sysFile);
        result.setData(sysFile);
        return result;
    }


    private static void setCellImage(XWPFTableCell cell, List<String> urlArray) {
        if (CollectionUtil.isEmpty(urlArray))
            return;
        List<XWPFParagraph> paragraphs = cell.getParagraphs();
        XWPFParagraph newPara = paragraphs.get(0);
        XWPFRun imageCellRunn = newPara.createRun();
        for (String url : urlArray) {
            File image = new File(url);
            if (!image.exists()) {
                continue;
            }

            int format;
            if (url.endsWith(".emf")) {
                format = XWPFDocument.PICTURE_TYPE_EMF;
            } else if (url.endsWith(".wmf")) {
                format = XWPFDocument.PICTURE_TYPE_WMF;
            } else if (url.endsWith(".pict")) {
                format = XWPFDocument.PICTURE_TYPE_PICT;
            } else if (url.endsWith(".jpeg") || url.endsWith(".jpg")) {
                format = XWPFDocument.PICTURE_TYPE_JPEG;
            } else if (url.endsWith(".png")) {
                format = XWPFDocument.PICTURE_TYPE_PNG;
            } else if (url.endsWith(".dib")) {
                format = XWPFDocument.PICTURE_TYPE_DIB;
            } else if (url.endsWith(".gif")) {
                format = XWPFDocument.PICTURE_TYPE_GIF;
            } else if (url.endsWith(".tiff")) {
                format = XWPFDocument.PICTURE_TYPE_TIFF;
            } else if (url.endsWith(".eps")) {
                format = XWPFDocument.PICTURE_TYPE_EPS;
            } else if (url.endsWith(".bmp")) {
                format = XWPFDocument.PICTURE_TYPE_BMP;
            } else if (url.endsWith(".wpg")) {
                format = XWPFDocument.PICTURE_TYPE_WPG;
            } else {
                System.out.println("Unsupported picture: " + url +
                        ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
                continue;
            }

            try (FileInputStream is = new FileInputStream(url)) {
                imageCellRunn.addPicture(is, format, image.getName(), Units.toEMU(80), Units.toEMU(115)); // 200x200 pixels
            } catch (Exception e) {
                e.printStackTrace();
            }
//            imageCellRunn.addBreak();

        }


    }


}
